package com.example.a1.myapplication.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.example.a1.myapplication.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
    //master1
    //master
    //bug
    //bug2
    private ImageView ivBack;
    private Button bList;
    private Camera mCamera;
    private Camera.Parameters parameters = null;
    private SurfaceView surfaceView;
    private ImageView bTakePicture;
    private ImageView ivBack1;
    private String mFilePath;
//    public static List<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片;
    private byte[] mData;
    private AlbumOrientationEventListener  mAlbumOrientationEventListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //设置statusBar颜色
            getWindow().setStatusBarColor(getResources().getColor(R.color.base_black));
        }
        setContentView(R.layout.activity_camera);

        ivBack = (ImageView) findViewById(R.id.ivBack);
        bList = (Button) findViewById(R.id.bList);
        bTakePicture = (ImageView) findViewById(R.id.bTakePicture);
        ivBack1 = (ImageView) findViewById(R.id.ivBack1);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        bTakePicture.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        ivBack1.setOnClickListener(this);
        bList.setOnClickListener(this);
        WindowManager wm1 = this.getWindowManager();
        int width1 = wm1.getDefaultDisplay().getWidth();
        int height1 = wm1.getDefaultDisplay().getHeight();
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceView.getHolder().setFixedSize(width1, height1); //设置Surface分辨率
        surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮
        surfaceView.getHolder().addCallback(new SurfaceCallback());//为SurfaceView的句柄添加一个回调函数

        mAlbumOrientationEventListener = new AlbumOrientationEventListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.ivBack:
//                selImageList.clear();
                finish();
                break;
            //返回
            case R.id.ivBack1:
//                selImageList.clear();
                finish();
                break;
            //列表
            case R.id.bList:
//                Intent intent = new Intent(context, SSPListActivity.class);
//                startActivity(intent);
                break;
            case R.id.bTakePicture:
//                showLoading("拍照中...");
                mCamera.takePicture(null, null, new MyPictureCallback());
                break;
        }
    }

    private final class MyPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            mData = data;
            try {
                    mFilePath = saveToSDCard(mData); // 保存图片到sd卡中
//                    ImageItem item = new ImageItem();
//                    item.path = mFilePath;
//                    selImageList.add(item);
//                    Intent intent = new Intent(context, SSPDetailActivity.class);
//                    intent.putExtra("file", (Serializable) selImageList);
//                    startActivity(intent);
//                    showToast("拍照成功");
//                    hideLoading();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取保存图片的目录
     *
     * @return
     */
    public static File getAlbumDir() {
        File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "inossem");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }
    /**
     * 将拍下来的照片存放在SD卡中
     *
     * @param data
     * @throws IOException
     */
    public String saveToSDCard(byte[] data) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = getAlbumDir();
        File jpgFile = new File(fileFolder, filename);
        Bitmap bitmap = null;
        BufferedOutputStream bos = null;
        try {
//            bos = new BufferedOutputStream(new FileOutputStream(jpgFile));
//            bitmap = getMatrixBitmap(data);
//            bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bos);//将图片压缩到流中
//            bos.flush();//输出
//            bos.close();//关闭

            FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
            outputStream.write(data); // 写入sd卡中
            outputStream.close(); // 关闭输出流
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileFolder.getAbsolutePath() + "/" + filename;
    }


    private final class SurfaceCallback implements SurfaceHolder.Callback {
        // 拍照状态变化时调用该方法
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            if (mAlbumOrientationEventListener.canDetectOrientation()) {
                mAlbumOrientationEventListener.enable();
            } else {
                Log.d("chengcj1", "Can't Detect Orientation");
            }
            // SurfaceView尺寸发生改变时（首次在屏幕上显示同样会调用此方法），初始化mCamera参数，启动Camera预览
            parameters = mCamera.getParameters();// 获取mCamera的参数对象
            parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
            Point point = new Point();
            point.x = width;
            point.y = height;
            point = getBestCameraResolution(parameters, point);
            parameters.setPreviewSize(point.x, point.y);// 设置预览图片尺寸
            Camera.Size largestSize = getBestSupportedSize(parameters.getSupportedPictureSizes());// 设置捕捉图片尺寸
            parameters.setPictureSize(largestSize.width, largestSize.height);
            List<String> focusModes = parameters.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            }
            parameters.set("orientation", "portrait");
            parameters.set("rotation", 90);
            mCamera.setParameters(parameters);
            mCamera.setDisplayOrientation(90);
            try {
                mCamera.startPreview();
                mCamera.cancelAutoFocus();// 2如果要实现连续的自动对焦，这一句必须加上
            } catch (Exception e) {
                if (mCamera != null) {
                    mCamera.release();
                    mCamera = null;
                }
            }
        }

        // 开始拍照时调用该方法
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // SurfaceView创建时，建立Camera和SurfaceView的联系
            if (mCamera != null) {
                try {
                    mCamera.setPreviewDisplay(holder);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        // 停止拍照时调用该方法
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            mAlbumOrientationEventListener.disable();
            // SurfaceView销毁时，取消Camera预览
            if (mCamera != null) {
                mCamera.stopPreview();
            }
        }

    }

    private Point getBestCameraResolution(Camera.Parameters parameters, Point screenResolution) {
        float tmp = 0f;
        float mindiff = 100f;
        float x_d_y = (float) screenResolution.x / (float) screenResolution.y;
        Camera.Size best = null;
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        for (Camera.Size s : supportedPreviewSizes) {
            tmp = Math.abs(((float) s.height / (float) s.width) - x_d_y);
            if (tmp < mindiff) {
                mindiff = tmp;
                best = s;
            }
        }
        return new Point(best.width, best.height);
    }

    private Camera.Size getBestSupportedSize(List<Camera.Size> sizes) {
        // 取能适用的最大的SIZE
        Camera.Size largestSize = sizes.get(0);
        int largestArea = sizes.get(0).height * sizes.get(0).width;
        for (Camera.Size s : sizes) {
            int area = s.width * s.height;
            if (area > largestArea) {
                largestArea = area;
                largestSize = s;
            }
        }
        return largestSize;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 开启相机
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            mCamera = Camera.open(0);
            // i=0 表示后置相机
        } else
            mCamera = Camera.open();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 释放相机
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_CAMERA: // 按下拍照按钮
                if (mCamera != null && event.getRepeatCount() == 0) {
                    // 拍照
                    //注：调用takePicture()方法进行拍照是传入了一个PictureCallback对象——当程序获取了拍照所得的图片数据之后
                    //，PictureCallback对象将会被回调，该对象可以负责对相片进行保存或传入网络
                    mCamera.takePicture(null, null, new MyPictureCallback());
                }
        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            selImageList.clear();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public class AlbumOrientationEventListener extends OrientationEventListener {

        public AlbumOrientationEventListener(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            if (ORIENTATION_UNKNOWN == orientation) {
                return;
            }
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(0, info);
            orientation = (orientation + 45) / 90 * 90;
            int rotation = 0;
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                rotation = (info.orientation - orientation + 360) % 360;
            } else {
                rotation = (info.orientation + orientation) % 360;
            }
            Log.e("TAG","orientation: " + orientation);
            if (null != mCamera) {
                Camera.Parameters parameters = mCamera.getParameters();
                parameters.setRotation(rotation);
                mCamera.setParameters(parameters);
            }
        }
    }
}
